"""
IOT MCP Server 主入口文件

基于 FastAPI 的 IOT MCP Server API
"""

import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware

from app.config.settings import settings
from app.api.routes import (
    MCP_PROTOCOL_VERSION,
    router,
    http_exception_handler,
    general_exception_handler,
)
from app.utils.logger import get_logger


logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时加载模型
    logger.info("📦 初始化资源")
    # 在应用启动时调用
    yield

    # 关闭时清理资源
    logger.info("❌ 关闭 IOT MCP服务器...")
    logger.info("❌ 资源清理完成")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    description=settings.app_description,
    version=settings.app_version,
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
)

# 包含API路由
app.include_router(router)

# 注册异常处理器
app.add_exception_handler(HTTPException, http_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)

# 添加中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


async def main_server():
    import uvicorn

    """启动MCP服务器"""
    logger.info("🚀 启动IOT MCP服务器...")
    logger.info(f"📋 协议版本: {MCP_PROTOCOL_VERSION}")
    logger.info(f"🚄 传输类型: Streamable HTTP")
    logger.info(f"📡 MCP端点: http://{settings.host}:{settings.port}/mcp")
    logger.info(f"📚 健康检查: http://{settings.host}:{settings.port}/health")
    logger.info(f"启动服务器: {settings.host}:{settings.port}")

    config = uvicorn.Config(
        app,
        host=settings.host,
        port=settings.port,
        log_level=settings.log_level.lower(),
    )
    uvicorn_server = uvicorn.Server(config)
    await uvicorn_server.serve()
    # uvicorn.run(
    #     app,
    #     host=settings.host,
    #     port=settings.port,
    #     log_level=settings.log_level.lower(),
    # )


def main():
    asyncio.run(main_server())


if __name__ == "__main__":
    main()
